package com.waitingsnow.core.service
{
import com.waitingsnow.core.debug.Logger;

import flash.events.AsyncErrorEvent;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.NetStatusEvent;
import flash.events.SecurityErrorEvent;
import flash.net.NetConnection;
import flash.net.ObjectEncoding;
import flash.net.Responder;

/**
 * 
 * @author waitingsnow
 * $Id: AmfService.as 2 2012-05-17 10:10:03Z cgslendy@gmail.com $
 */
public class AmfService extends EventDispatcher
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	/**
	 * Constructs a new <code>AmfService</code> instance.
	 * 
	 */
	public function AmfService(gateway:String)
	{
		_gateway = gateway;
		_nc = new NetConnection();
		_nc.objectEncoding = ObjectEncoding.AMF3;
		_nc.client = this;
		_nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
		_nc.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		_nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
		_nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		_nc.connect(_gateway);
		Logger.log("connect: " + _gateway);
	}
	
	//==========================================================================
	//  Variables
	//==========================================================================
	private var _nc:NetConnection;
	private var _gateway:String;
	
	//==========================================================================
	//  Methods
	//==========================================================================
	public function call(methodName:String, responder:Responder, ...args):void
	{
		args.unshift(responder);
		args.unshift(methodName);
		_nc.call.apply(null, args);
	}
	
	//==========================================================================
	//  Event Handlers
	//==========================================================================
	private function netStatusHandler(event:NetStatusEvent):void
	{
		if (event.info.code == "NetConnection.Connect.Success")
		{
			Logger.log("connect success");
		}
		else
		{
			Logger.log("connect failer" + event.info.code);
		}
	}
	
	private function ioErrorHandler(event:IOErrorEvent):void 
	{
		Logger.log("io error");
	}
	
	private function asyncErrorHandler(event:AsyncErrorEvent):void 
	{
		Logger.log("async error");
	}
	
	private function securityErrorHandler(event:SecurityErrorEvent):void 
	{
		Logger.log("security error");
	}
}
}